<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;


class BuildingModel extends Model
{


    use SoftDelete;
    

    // 表名
    protected $name = 'building';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    
    public function rooms()
    {
        return $this->hasMany('app\admin\model\BuildingRoomModel', 'build_id', 'id');
    }

    public function belongUser()
    {
        return $this->belongsTo(\app\common\model\User::class, 'user_id', 'id')->bind('username');
    }
    public function delUser()
    {
        return $this->belongsTo(\app\common\model\User::class, 'del_uid', 'id')->bind('username');
    }

    public static function getUserBuildingIds($user_id)
    {
        $ids = self::where("find_in_set($user_id,user_id)")->column('id');
        $user = User::get($user_id);
        if ($user) {
            $staff_build_ids = StaffModel::where('mobile', $user->mobile)->column('build_ids');
            foreach ($staff_build_ids as $item) {
                if (!empty($item)) {
                    $ids = array_merge($ids, explode(',', $item));
                }
            }
        }
        return $ids;
    }

    public function getImagesAttr($value, $data)
    {
        $value = $value ?: ($data['images'] ?? []);
        $images = $value ? json_decode($value, true) : [];
        foreach ($images as $k =>$v) {
            $images[$k] = cdnurl($v);
        }
        return $images;
    }

    public function setImagesAttr($value)
    {
        if (empty($value)) return null;
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['update_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['delete_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
